package com.rchat.pocmini.activity.ble;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.rchat.pocmini.R;
import com.rchat.pocmini.bean2eventbus.BleBean;
import com.rchat.pocmini.bean2eventbus.ConnectBleBean;
import com.rchat.pocmini.service.PocService;

import org.greenrobot.eventbus.EventBus;

import java.util.List;


/**
 * Created by ljd on 2017/8/29.
 */

public class ScanBleResultAdapter extends BaseAdapter {

    interface IItemTouchHelperAdapter {
        void onClickBleConnect(BleBean bean);
    }

    private List<BleBean> data;
    private LayoutInflater inflater;

    private IItemTouchHelperAdapter mItemTouchHelperAdapterImpl;

    public ScanBleResultAdapter(Context context, List<BleBean> data) {
        this.data = data;
        inflater = LayoutInflater.from(context);
    }

    public void setItemTouchHelperListener(IItemTouchHelperAdapter listener) {
        mItemTouchHelperAdapterImpl = listener;
    }

    @Override
    public int getCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(0);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.ble_item, null);
            holder = new ViewHolder();
            holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
            holder.btnConnect = (Button) convertView.findViewById(R.id.btn_connect);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final BleBean bean = data.get(position);
        String name = "NULL".equals(bean.getResult().getName()) ? "未知设备" : bean.getResult().getName();
        holder.tvName.setText(bean.getResult().getAddress() + ":" + name);
        holder.btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mItemTouchHelperAdapterImpl != null){
                    mItemTouchHelperAdapterImpl.onClickBleConnect(bean);
                }

            }
        });
        if (bean.isConnected()) {
            holder.btnConnect.setText("已连接");
//            holder.btnConnect.setClickable(false);
        } else {
            holder.btnConnect.setText("连接");
//            holder.btnConnect.setClickable(true);
        }
        return convertView;
    }

    static class ViewHolder {
        TextView tvName;
        Button btnConnect;
    }
}
